﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;
using UnityEngine.Experimental.Director;

public class TestAnimator : MonoBehaviour {
    public GameObject body;
    public GameObject face;
    public GameObject hair;

    [ButtonCallFunc()]
    public bool Merge;
    public void MergeMethod()
    {
        var b = GameObject.Instantiate<GameObject>(body);
        operateModel = b;


        BindMeshObj(b, hair);
        var f = GameObject.Instantiate<GameObject>(face);
        BindFaceObject(b, f);
    }

    private void BindMeshObj(GameObject ParentGameObj, GameObject SubObj)
    {
        if (SubObj == null || ParentGameObj == null)
        {
            return;
        }

        var g = new GameObject(SubObj.name);
        g.transform.parent = ParentGameObj.transform;
        g.transform.localPosition = Vector3.zero;
        g.transform.localRotation = Quaternion.identity;
        g.transform.localScale = Vector3.one;
        m_SkinMeshPart = g;
        //SubObj.gameObject.SetActive(false);
        MathUtils.SetLayer(g, ParentGameObj.layer);

        var render = g.AddComponent<SkinnedMeshRenderer>();
        var copyRender = SubObj.GetComponentInChildren<SkinnedMeshRenderer>();
        var copyPart = copyRender.gameObject;
        MathUtils.SetBones(g, copyPart, ParentGameObj);
        render.sharedMesh = copyRender.sharedMesh;
        render.sharedMaterials = copyRender.sharedMaterials;
    }

    private void BindFaceObject(GameObject ParentGameObj, GameObject SubObj)
    {
        if (ParentGameObj == null || SubObj == null)
        {
            return;
        }
        var faceSlot = MathUtils.FindChildRecursive(ParentGameObj.transform, "B_Face");
        SubObj.transform.parent = faceSlot.transform;
        MathUtils.InitGameObject(SubObj);
    }

    private GameObject m_SkinMeshPart;
    public GameObject operateModel;


    public AnimationClip aniObj;
    [ButtonCallFunc()]
    public bool LoadAni;
    public void LoadAniMethod()
    {
        clips = new List<AnimationClip>();
        var path = AssetDatabase.GetAssetPath(aniObj);
        var dir = System.IO.Path.GetDirectoryName(path);
        var folder = new DirectoryInfo(dir);
        foreach (var f in folder.GetFiles("*.anim"))
        {
            var st = f.FullName.IndexOf("Assets");
            var partName = f.FullName.Substring(st);

            var aniClip = AssetDatabase.LoadAssetAtPath<AnimationClip>(partName);
            //Debug.Log("aniName:"+aniClip);
            clips.Add(aniClip);
        }
    }

    [ListCallFunc()]
    public List<AnimationClip> clips;

    public void clipsMethod(int did)
    {
        var ani = operateModel.GetComponent<Animator>();
        var playable = AnimationClipPlayable.Create(clips[did]);
        ani.Play(playable);

    }
}
